//
//  KeepVC.m
//  NotepadApp
//
//  Created by yobet on 2018/4/16.
//  Copyright © 2018年 HJ. All rights reserved.
//

#import "KeepVC.h"
#import "CCDatePickerView.h"
#import "WeatherConditionsVC.h"

@interface KeepVC ()<UITextViewDelegate,AMapLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet UIView *btmView;
@property (weak, nonatomic) IBOutlet UITextView *content;
@property (weak, nonatomic) IBOutlet UILabel *placeHolder;
@property (weak, nonatomic) IBOutlet UIImageView *image1;
@property (weak, nonatomic) IBOutlet UIImageView *image2;
@property (weak, nonatomic) IBOutlet UIButton *locationBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *layoutH;
@property (weak, nonatomic) IBOutlet UILabel *locationStr;
@property (weak, nonatomic) IBOutlet UIButton *weather;

@property(nonatomic,strong)AMapLocationManager * location;


@end

@implementation KeepVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.leftNavImageName= @"back";
    self.rightNavTitle = @"保存";
    self.navTitle = [CommonTools getCurrentTimes:YES isYear:YES];
    self.content.delegate = self;
    [self.locationBtn setImage:[UIImage imageNamed:@"定位"] forState:UIControlStateNormal];
    [self.weather setImage:[UIImage imageNamed:@"天气"] forState:UIControlStateNormal];
    [self locationInit];
    [self startSerialLocation];
//    [self createFMDB];
}

-(void)locationInit {
    self.location = [[AMapLocationManager alloc] init];
    [self.location setDelegate:self];
    
    [self.location setPausesLocationUpdatesAutomatically:NO];
    
    [self.location setAllowsBackgroundLocationUpdates:YES];

}
- (void)startSerialLocation
{
    //开始定位
    [self.location startUpdatingLocation];
}

- (void)stopSerialLocation
{
    //停止定位
    [self.location stopUpdatingLocation];
}

- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error
{
    //定位错误
    NSLog(@"%s, amapLocationManager = %@, error = %@", __func__, [manager class], error);
}

- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location {
    CLGeocoder *clGeoCoder = [[CLGeocoder alloc] init];
    CLLocation *cl = [[CLLocation alloc] initWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
    [clGeoCoder reverseGeocodeLocation:cl completionHandler: ^(NSArray *placemarks,NSError *error) {
        
        for (CLPlacemark *placeMark in placemarks) {
            NSDictionary *addressDic = placeMark.addressDictionary;
            NSString *state=[addressDic objectForKey:@"State"];
            NSString *city=[addressDic objectForKey:@"City"];
            NSString *subLocality=[addressDic objectForKey:@"SubLocality"];
            NSString *street=[addressDic objectForKey:@"Street"];
            NSString * allLocationStr =[NSString stringWithFormat:@"%@%@%@%@",state,city,subLocality,street];
            NSLog(@"%@", allLocationStr);
            [self.location stopUpdatingLocation];
            self.locationStr.text = allLocationStr;
        }
    }];
}

-(void)textViewDidChange:(UITextView *)textView {//根据字长度判断是否隐藏占位符Label
    textView.scrollEnabled = NO;
    CGSize size = [self sizeWithString:textView.text font:[UIFont systemFontOfSize:14] width:textView.width];
    _layoutH.constant = size.height+10;
}

-(CGSize)sizeWithString:(NSString*)string font:(UIFont*)font width:(float)width {
    
    CGRect rect = [string boundingRectWithSize:CGSizeMake(width, 80000) options:NSStringDrawingTruncatesLastVisibleLine |   NSStringDrawingUsesFontLeading |NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];
    return rect.size;
}

-(void)didClickLeftNavAction {
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)didClickRightNavAction {
    
    [self insertFMDBWithlist:self.content.text address:self.locationStr.text image:self.data time:self.navTitle];
    [self dismissViewControllerAnimated:YES completion:nil];
    [mNotificationCenter postNotificationName:@"keepVCNotification" object:nil];
}

- (IBAction)btmAllBtn:(UIButton *)sender {
    if (sender.tag==0) {
        [self startSerialLocation];
    }else if (sender.tag==1) {
        WeatherConditionsVC * WCVC =[[WeatherConditionsVC alloc]init];
        WCVC.block = ^(NSString *imageStr) {
            [self.weather setImage:[UIImage imageNamed:imageStr] forState:UIControlStateNormal];
        };
        [self.navigationController pushViewController:WCVC animated:YES];
    }else if (sender.tag==2) {
        [TZImagePickerTool selectImageFrom:self complete:^(UIImage *img) {
            self.image1.image = img;
            self.data = UIImagePNGRepresentation(img);
        }];
    }else {
        CCDatePickerView *datePicker = [[CCDatePickerView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        [self.view addSubview:datePicker];
        datePicker.chooseTimeLabel.text = @"选择时间";
        WeakSelf;
        datePicker.blcok = ^(NSDate *dateString) {
            weakSelf.navTitle = [NSString stringWithFormat:@"%ld-%ld-%ld %ld:%ld",(long)dateString.year,(long)dateString.month,(long)dateString.day,(long)dateString.hour,(long)dateString.minute];
        };
        [datePicker fadeIn];
    }
}

-(BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    self.placeHolder.hidden = YES;
    return YES;
}
-(void)textViewDidEndEditing:(UITextView *)textView {
    if (textView.text.length<1) {
        self.placeHolder.hidden = NO;
    }
}

#pragma mark -- 插入数据库
-(void)insertFMDBWithlist:(NSString *)content address:(NSString *)address image:(NSData *)image time:(NSString *)time {
    if ([self.db open]) {
        [self.db executeUpdateWithFormat:@"INSERT INTO t_Keep (content, address, image, time) VALUES (%@, %@, %@, %@);", content,address,image,time];
    }
    [self.db close];
}

@end
